from decimal import Decimal
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated

from goods.models import SKU
# Create your views here.
from orders.serializers import OrderSettlementSerializer, SaveOrderSerializer


class OrderSettlementView(APIView):
    """
    订单结算
    """
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        订单页面数据展示
        :param request:
        :return:
        """
        # 取出用户
        user = request.user
        # 从redis中取出选中的商品
        redis_conn = get_redis_connection('cart')
        cart_dict = redis_conn.hgetall('cart_%s' % user.id)
        # {
        #     cart_user_id :{
        #         sku_id : count
        #     }
        # }
        cart_selected = redis_conn.smembers('cart_selected_%s' % user.id)
        # 遍历所有数据把勾选的商品sku_id,和哈希中的sku_id的count取出
        cart = {}
        for sku_id in cart_selected:
            cart[int(sku_id)] = int(cart_dict[sku_id])

        sku_obj_list = SKU.objects.filter(id__in=(cart.keys()))

        for sku in sku_obj_list:
            sku.count = cart[sku.id]
        # 商品价格
        # 运费
        freight = Decimal('10.00')
        # 序列化
        serialzier = OrderSettlementSerializer({'freight': freight, 'skus': sku_obj_list})
        # return

        return Response(serialzier.data)


class SaveOrderView(CreateAPIView):
    """
    保存订单
    """
    permission_classes = [IsAuthenticated]
    serializer_class = SaveOrderSerializer
